'''
dbus_server.py

Copyright 2009 Xavier Mendez Navarro aka Javi

This file is part of pysqlin

pysqlin is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.

pysqlin is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with pysqlin; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
'''
import gobject
import dbus
import dbus.service
import dbus.mainloop.glib

import sys

import logging

from framework.interfaces import IPlugin
from framework.baseclass import BPlugin
from lib.importer import Importer

class ImportObject(dbus.service.Object, Importer):
    @dbus.service.method("com.pysqlin.interface",
                         in_signature='as', out_signature='')
    def send_sqli(self, all_sqli):
	# expected tuple as (url, post_data, cookie, var, method, itype, db, db_error)
	url, post_data, cookie, var, method, itype, db, db_error = all_sqli
	db = self.dbpstrike_to_dbpysqlin(db)
	db_error = self.dbpstrike_to_dbpysqlin(db_error)

	self.print_status("Received: %s [%s/%s/%s]" % (url, var, method, db))
	# str() all to avoid pickle errors with dbus strings objects
	self.sqlimport([str(url), str(post_data), str(cookie), str(var), str(method), str(itype), str(db), str(db_error)])

class DBusServer(Importer, IPlugin):
    def __init__(self, api):
	BPlugin.__init__(self, api)

	self.__logger = logging.getLogger('plugins.auxiliary.import.DBusServer')

    def load(self, api):
	return self

    def name(self): return "DBusServer importer"
    def description(self): 
	return """
	Imports sql injections from external apps through DBus interface.
	"""

    def init(self):
	pass

    def parameters(self): 
	return super(DBusServer, self).parameters()

    def commands(self): 
	return (
	    ('run', 'Launch DBusServer loop.', 'run', [], self.cmd_run),
	)

    def cmd_run(self, **event):
	dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

	try:
	    self.print_status("Creating dbus service: com.pysqlin.DBusServer.")
	    session_bus = dbus.SessionBus()
	    name = dbus.service.BusName("com.pysqlin.DBusServer", session_bus)
	    object = ImportObject(session_bus, '/ImportObject')
	except KeyError:
	    self.print_status("Dbus service already created.")
	    pass

	try:
	    self.print_status("Running dbus service.")
	    mainloop = gobject.MainLoop()
	    mainloop.run()
	except KeyboardInterrupt:
	    self.print_status("Exiting...")
	    mainloop.quit()
	    print

def load(api):
    return  DBusServer(api)


